package com.example.stuwork.controller;

import com.example.stuwork.common.Result;
import com.example.stuwork.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 认证控制器，处理登录和注册请求
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 管理员登录
     *
     * @param loginForm 登录表单，包含username和password
     * @return 登录结果
     */
    @PostMapping("/admin/login")
    public Result<?> adminLogin(@RequestBody Map<String, String> loginForm) {
        String username = loginForm.get("username");
        String password = loginForm.get("password");
        return authService.adminLogin(username, password);
    }

    /**
     * 教师登录
     *
     * @param loginForm 登录表单，包含teacherId和password
     * @return 登录结果
     */
    @PostMapping("/teacher/login")
    public Result<?> teacherLogin(@RequestBody Map<String, String> loginForm) {
        String teacherId = loginForm.get("teacherId");
        String password = loginForm.get("password");
        return authService.teacherLogin(teacherId, password);
    }

    /**
     * 学生登录
     *
     * @param loginForm 登录表单，包含studentId和password
     * @return 登录结果
     */
    @PostMapping("/student/login")
    public Result<?> studentLogin(@RequestBody Map<String, String> loginForm) {
        String studentId = loginForm.get("studentId");
        String password = loginForm.get("password");
        return authService.studentLogin(studentId, password);
    }

    /**
     * 学生注册
     *
     * @param registerForm 注册表单，包含studentId, name, password, email, phone, year, deptNumber, classId
     * @return 注册结果
     */
    @PostMapping("/student/register")
    public Result<?> studentRegister(@RequestBody Map<String, String> registerForm) {
        String studentId = registerForm.get("studentId");
        String name = registerForm.get("name");
        String password = registerForm.get("password");
        String email = registerForm.get("email");
        String phone = registerForm.get("phone");
        
        // 获取额外的信息
        String gender = registerForm.get("gender");
        String year = registerForm.get("year");
        String deptNumber = registerForm.get("deptNumber");
        String classIdStr = registerForm.get("classId");
        Long classId = null;
        
        // 将classId从字符串转换为Long
        if (classIdStr != null && !classIdStr.isEmpty()) {
            try {
                classId = Long.parseLong(classIdStr);
            } catch (NumberFormatException e) {
                return Result.error("班级ID格式不正确");
            }
        }
        
        return authService.studentRegister(studentId, name, gender, password, email, phone, year, deptNumber, classId);
    }
} 